package org.wsiz.vro.web.component;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.BeanValidator;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Lenient bean validator which disable validation in certain cases in order to let the user navigate to sub view without loosing the data entered in input field.  
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class LenientBeanValidator extends BeanValidator {
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) {
        if (doValidation(context)) {
            super.validate(context, component, value);
        }
    }

    private boolean doValidation(FacesContext context) {
        Map<String, String[]> requestParameterValuesMap = context.getExternalContext().getRequestParameterValuesMap();
        // save button present in main form
        if (requestParameterValuesMap.containsKey("form:save")) {
            return true;
        }

        // askForSaveDialogYes button present in ask for save dialog
        if (requestParameterValuesMap.containsKey("form:askForSaveDialogYes")) {
            return true;
        }

        // ok button present in sub-edit.
        if (requestParameterValuesMap.containsKey("form:ok")) {
            return true;
        }

        return false;
    }
}
